package net.stogi.dsper.ui.server.module.dataobject;

import net.stogi.common.gwt.dispatch.server.core.ActionHandler;
import net.stogi.common.gwt.dispatch.shared.exception.ActionException;
import net.stogi.common.security.service.SecurityService;
import net.stogi.dsper.api.service.UserService;
import net.stogi.dsper.ui.shared.module.dataobject.ListDataObjectsAction;
import net.stogi.dsper.ui.shared.module.dataobject.ListDataObjectsResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("DsperUi.Dispatch.ListDataObjectActionHandler")
public class ListDataObjectActionHandler implements ActionHandler<ListDataObjectsAction, ListDataObjectsResult> {

	private static final Logger log = LoggerFactory.getLogger(ListDataObjectActionHandler.class);

	@Autowired
	private SecurityService securityService;

	@Autowired
	private UserService userService;

	@Override
	public ListDataObjectsResult execute(ListDataObjectsAction action) throws ActionException {
		log.trace("execute(): invoke: [ action = '{}']", action);

		ListDataObjectsResult result;

		try {
			Long userId = userService.getUserByUsername(securityService.getLoggedUserPrincipalData().getUsername()).getId();

			result = new ListDataObjectsResult(userService.listDataObjects(userId));
		}
		catch (Exception e) {
			throw new ActionException(e);
		}

		return result;
	}

	@Override
	public Class<ListDataObjectsAction> getActionType() {
		return ListDataObjectsAction.class;
	}

	@Override
	public void rollback(ListDataObjectsAction action, ListDataObjectsResult result) throws ActionException {}
}
